import * as $textbook from '@/api/textbook'
import course from '@/dict/course'

export const UPDATE_TEXTBOOKS = 'update_textbooks'
export const UPDATE_OPEN_IDS = 'update_open_ids'
export const UPDATE_CURRENT_OPEN_ID = 'update_current_open_id'
export const UPDATE_CURRENT_COURSE_ID = 'update_current_course_id'

const state = () => {
  return {
    textbooks: [],
    isPageLoaded: false,
    openIds: [],
    currentOpenId: 0,
    currentCourseId: 0
  }
}

const getters = {
  textbooks (state) {
    let t = state.textbooks.map(n => {
      let courses = [...n.courses]
      courses = courses.map(nn => {
        let c = {
          id: nn.id,
          name: nn.name,
          checked: state.currentCourseId === nn.id
        }
        return c
      })
      let tb = {
        id: n.id,
        name: n.name,
        courses,
        opened: state.currentOpenId === n.id
      }
      return tb
    })
    return t
  },
  selectCourse (state) {
    let t = course
    if (!state.currentCourseId) return t
    state.textbooks.forEach(n => {
      if (!n.courses) return
      n.courses.forEach(nn => {
        if (nn.id !== state.currentCourseId) return
        t = nn
      })
    })
    return t
  }
}

const actions = {
  async handleInit ({ commit, state, rootState }) {
    let rs = await $textbook.getAll()
    commit(UPDATE_TEXTBOOKS, rs)
  },
  handleToggleOpen ({ commit, state, rootState }, textbookId) {
    let id = state.currentOpenId === textbookId ? 0 : textbookId
    commit(UPDATE_CURRENT_OPEN_ID, id)
  },
  handleCourseSelect ({ commit, state, rootState }, courseId) {
    commit(UPDATE_CURRENT_COURSE_ID, courseId)
    wx.navigateBack()
  },
}

const mutations = {
  [UPDATE_TEXTBOOKS] (state, textbooks) {
    state.textbooks = textbooks
  },
  [UPDATE_OPEN_IDS] (state, openIds) {
    state.openIds = [...openIds]
  },
  [UPDATE_CURRENT_OPEN_ID] (state, textbookId) {
    state.currentOpenId = textbookId
  },
  [UPDATE_CURRENT_COURSE_ID] (state, courseId) {
    state.currentCourseId = courseId
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
